package com.example.limit.aspect;

import com.example.limit.fallback.RateLimiterHandler;
import com.example.limit.service.HybridRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class RateLimitAspect {
    
    @Autowired
    private HybridRateLimiter hybridRateLimiter;
    
    @Around("@annotation(rateLimit)")
    public Object around(ProceedingJoinPoint point, RateLimit rateLimit) throws Throwable {
        String module = rateLimit.module();
        
        // 尝试获取限流许可
        boolean acquired = hybridRateLimiter.tryAcquire(module);
        
        if (acquired) {
            // 获取成功，执行业务逻辑
            return point.proceed();
        } else {
            // 限流触发后处理
            log.warn("触发限流，module: {}, method: {}", module, point.getSignature().getName());
            RateLimiterHandler limiterHandler = rateLimit.fallback().newInstance();
            return limiterHandler.handle(point);
        }
    }

}